/*
 * ============================================================================
 *                   GNU Lesser General Public License
 * ============================================================================
 *
 *
 *
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307, USA.
 * 
 *
 *
 */
package rad.framework.jpa;

import java.sql.Connection;
import java.sql.PreparedStatement;

import javax.naming.InitialContext;
import javax.sql.DataSource;
import javax.transaction.UserTransaction;

/**
 * Extend this script to populate persistence data for a test.
 * 
 * @author boudyacho
 * 
 */
public abstract class JdbcScript {
	private String dataSourceJndiName = "";

	private InitialContext ctx = null;

	/**
	 * @param jndiName
	 *            of the EntityManagerFactory
	 */
	protected JdbcScript(String dataSourceJndiName) {
		this.dataSourceJndiName = dataSourceJndiName;
	}

	public Object run() {
		try {
			DataSource ds = (DataSource) lookup(dataSourceJndiName);
			Connection connection = ds.getConnection();
			UserTransaction t = (UserTransaction) lookup("UserTransaction");
			t.begin();
			try {
				Object o = persist(connection);// do the work
				t.commit();
				return o;
			} catch (Exception e) {
				t.rollback();
				throw e;
			} finally {
				connection.close();
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	protected Object lookup(String name) throws Exception {
		if (ctx == null) {
			ctx = new InitialContext();
		}
		return ctx.lookup(name);
	}

	/**
	 * Implement this to do the work.
	 */
	protected abstract Object persist(Connection connection) throws Exception;

	/**
	 * @param name
	 *            of table
	 * @param datasource
	 *            jndi name
	 * @throws Exception
	 */
	public static Integer clearTable(final String name, final String datasource) {
		return (Integer) (new JdbcScript(datasource) {

			@Override
			protected Object persist(Connection connection) throws Exception {
				PreparedStatement ps = connection
						.prepareStatement("delete from " + name);
				return new Integer(ps.executeUpdate());
			}
		}).run();
	}
}
